package be.jaisy.ui.httpservlet.extender.util;

import java.util.ArrayList;
import java.util.List;

import org.osgi.framework.Bundle;

/**
 * @author Stany Blanvalet
 */
public class ManifestParserHelper {

	private static ManifestParserHelper INSTANCE;
	
	private ManifestParserHelper() {
		super();
	}
	
	public static ManifestParserHelper getInstance(){
		if(INSTANCE==null)
			INSTANCE = new ManifestParserHelper();
		return INSTANCE;
	}

	public List<servletMappingContribution> getServletContribution(Bundle bundle) {
		List<servletMappingContribution> result = new ArrayList<servletMappingContribution>();
		String header = (String) bundle.getHeaders().get("HttpServletExtender-ServletContribution");
		if (header != null) {
			String clauses[] = header.split(",");
			for (int i = 0; i < clauses.length; i++) {
				String parts[] = clauses[i].trim().split("\\s*;\\s*");
				if (parts.length == 2)
					result.add(new servletMappingContribution(parts[0], parts[1]));
			}
		}
		return result;
	}
	
	public List<ResourceMappingContribution> getResourceContribution(Bundle bundle) {
		List<ResourceMappingContribution> result = new ArrayList<ResourceMappingContribution>();
		String header = (String) bundle.getHeaders().get("HttpServletExtender-ResourceContribution");
		if (header != null) {
			String clauses[] = header.split(",");
			for (int i = 0; i < clauses.length; i++) {
				String parts[] = clauses[i].trim().split("\\s*;\\s*");
				if (parts.length == 3)
					result.add(new ResourceMappingContribution(parts[0], parts[1], parts[2]));				
			}
		}
		return result;
	}
	
	public class servletMappingContribution{
	
		private String alias;
		private String className;
		
		public servletMappingContribution(String alias, String className) {
			super();
			this.alias = alias;
			this.className = className;
		}

		public String getAlias() {
			return alias;
		}

		public String getClassName() {
			return className;
		}
	}

	public class ResourceMappingContribution{
		
		private String alias;
		private String bundlePath;
		private String defaultPage;
		
		public ResourceMappingContribution(String alias, String budleLocation, String defaultPage) {
			super();
			this.alias = alias;
			this.bundlePath = budleLocation;
			this.defaultPage = defaultPage;
		}

		public String getAlias() {
			return alias;
		}

		public String getBundlePath() {
			return bundlePath;
		}

		public String getDefaultPage() {
			return defaultPage;
		}
	}

}
